package com.nuist.java_gobang.api;


import com.nuist.java_gobang.model.User;
import com.nuist.java_gobang.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    // 这个注解是直接将返回值写入HTTP响应体中,不许要解析为视图名
    public Object login(String username, String password, HttpServletRequest request){
        // 关键操作就是根据username 去数据库中查询
        // 如果能找到匹配的用户, 且密码一致, 则为登录成功
        User user = userMapper.selectByName(username);
        log.info("用户名: {}", username);
        System.out.println("[login] username=" + username);

        if(user == null || !user.getPassword().equals(password)){
            log.info("登录失败");
            return new User();
        }
        log.info("登录成功");

        HttpSession httpSession = request.getSession(true);
        // 获取或创建HTTP会话：getSession(true) 方法会返回当前请求关联的 HttpSession 对象
        //参数true的含义：如果当前没有会话，则创建一个新的会话；如果已有会话，则返回现有会话
        //会话用途：HttpSession 用于在多个HTTP请求之间存储用户相关的数据，实现状态保持
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password){
        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            User user = new User();
            return user;
        }
        // 由于可能会出现插入失败的错误,因此使用try catch 进行包裹
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest  request){
        try{
            HttpSession httpSession = request.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            return user;
        }catch (NullPointerException e){
            return new User();
        }
        // 可能会出现空指针异常, 因此也使用try catch 包裹
    }
}
